package yyy.ab.modules.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import yyy.ab.common.core.BaseServiceImpl;
import yyy.ab.modules.system.entity.SysMenu;
import yyy.ab.modules.system.entity.vo.SysMenuVo;
import yyy.ab.modules.system.mapper.SysMenuMapper;
import yyy.ab.modules.system.service.SysMenuService;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class SysMenuServiceImpl extends BaseServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Override
    public List<SysMenu> findByUser(Long currentUserId) {
        List<SysMenu> sysMenus = baseMapper.selectList(new QueryWrapper<SysMenu>().lambda()
                .ne(SysMenu::getType, 2)
                .eq(SysMenu::getHidden, false)
                .orderByAsc(SysMenu::getSort));
        return sysMenus;
    }

    @Override
    public List<SysMenu> buildTree(List<SysMenu> menus) {
        List<SysMenu> trees = new ArrayList<>();
        Set<Long> ids = new HashSet<>();
        for (SysMenu menuDTO : menus) {
            if (menuDTO.getPid() == null) {
                trees.add(menuDTO);
            }
            for (SysMenu it : menus) {
                if (menuDTO.getId().equals(it.getPid())) {
                    if (menuDTO.getChildren() == null) {
                        menuDTO.setChildren(new ArrayList<>());
                    }
                    menuDTO.getChildren().add(it);
                    ids.add(it.getId());
                }
            }
        }
        if (trees.size() == 0) {
            trees = menus.stream().filter(s -> !ids.contains(s.getId())).collect(Collectors.toList());
        }
        return trees;
    }

    @Override
    public List<SysMenuVo> buildMenus(List<SysMenu> menuDtos) {
        List<SysMenuVo> list = new LinkedList<>();
        menuDtos.forEach(menuDTO -> {
                    if (menuDTO != null) {
                        List<SysMenu> menuDtoList = menuDTO.getChildren();
                        SysMenuVo menuVo = new SysMenuVo();
                        menuVo.setTitle(menuDTO.getTitle());
                        menuVo.setHref(menuDTO.getPath());
                        menuVo.setIcon(menuDTO.getIcon());
                        // 如果不是外链
                        if (!menuDTO.getIFrame()) {
                            menuVo.setTarget("_self");
                        } else {
                            menuVo.setTarget("_target");
                        }
                        if (menuDtoList != null && menuDtoList.size() != 0) {
                            menuVo.setChild(buildMenus(menuDtoList));
                        }
                        list.add(menuVo);
                    }
                }
        );
        return list;
    }
}
